package com.ajax; /**
 * @author wzm
 * @create 2023-05-17 15:26
 */

import com.ajax.entity.User;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/jsonServlet")
public class JSONServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");


        //此时post请求过来以后是请求体的方式
        BufferedReader reader = request.getReader();
        //获取到请求的字符串
        String s = reader.readLine();

        //在java中需要使用Java对象来进行操作   字符串->java对象
        User user = JSON.parseObject(s, User.class);
        System.out.println("user = " + user);
        //使用该对象可以调用service方法

        System.out.println("-----------------------------------------");
        //模拟查询到了单个对象的集合 相应给客户端  java->字符串
        String s1 = JSON.toJSONString(user);

//        response.setContentType("application/json;charset=utf-8");
        response.setContentType("text/json;charset=utf-8");
        //将字符串相应给客户端
        //response.getWriter().write(s1);


        //相应一个集合到客户端
        List<User> list = new ArrayList<>();
        list.add(new User(1,"张三",15));
        list.add(new User(2,"李四",20));
        list.add(new User(3,"王五",30));
        list.add(new User(4,"钱六",40));

        String s2 = JSON.toJSONString(list);
        response.getWriter().write(s2);

    }
}
